package com.freecloud.bitorrent.domain.server.handler;

import com.freecloud.bitorrent.demo.bo.RequestMessage;
import com.freecloud.bitorrent.demo.bo.ResponseMessage;
import com.freecloud.bitorrent.domain.server.support.DhtCommandFactory;
import com.freecloud.bitorrent.enums.MessageTypeEnum;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * DHTServerHandler
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class DHTServerHandler extends SimpleChannelInboundHandler<RequestMessage> {

    private final DhtCommandFactory dhtCommandFactory;

    public DHTServerHandler(DhtCommandFactory dhtCommandFactory) {
        this.dhtCommandFactory = dhtCommandFactory;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, RequestMessage requestMessage)
        throws Exception {
        channelHandlerContext.executor().execute(() -> {
            log.info("requestMessage : {}", requestMessage);
            if (!MessageTypeEnum.Query.equals(requestMessage.getMessageType())) {
                log.info("其他结果，暂时不处理 : {}", requestMessage);
                return;
            }
            ResponseMessage responseMessage =
                dhtCommandFactory.getDhtCommand(requestMessage.getQuery()).response(requestMessage);
            log.info("responseMessage : {} -- requestMessage: {}", responseMessage, requestMessage);
        });
    }
}